{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "220db57c-608d-4ebd-8e5d-97486477bc8e",
   "metadata": {},
   "source": [
    "# Infinite Zoom Stable Diffusion v2 and OpenVINO™\n",
    "\n",
    "Stable Diffusion v2 is the next generation of Stable Diffusion model a Text-to-Image latent diffusion model created by the researchers and engineers from [Stability AI](https://stability.ai/) and [LAION](https://laion.ai/). \n",
    "\n",
    "General diffusion models are machine learning systems that are trained to denoise random gaussian noise step by step, to get to a sample of interest, such as an image.\n",
    "Diffusion models have shown to achieve state-of-the-art results for generating image data. But one downside of diffusion models is that the reverse denoising process is slow. In addition, these models consume a lot of memory because they operate in pixel space, which becomes unreasonably expensive when generating high-resolution images. Therefore, it is challenging to train these models and also use them for inference. OpenVINO brings capabilities to run model inference on Intel hardware and opens the door to the fantastic world of diffusion models for everyone!\n",
    "\n",
    "In previous notebooks, we already discussed how to run [Text-to-Image generation and Image-to-Image generation using Stable Diffusion v1](../stable-diffusion-text-to-image/stable-diffusion-text-to-image.ipynb) and [controlling its generation process using ControlNet](./controlnet-stable-diffusion/controlnet-stable-diffusion.ipynb). Now is turn of Stable Diffusion v2.\n",
    "\n",
    "## Stable Diffusion v2: What’s new?\n",
    "\n",
    "The new stable diffusion model offers a bunch of new features inspired by the other models that have emerged since the introduction of the first iteration. Some of the features that can be found in the new model are:\n",
    "\n",
    "* The model comes with a new robust encoder, OpenCLIP, created by LAION and aided by Stability AI; this version v2 significantly enhances the produced photos over the V1 versions. \n",
    "* The model can now generate images in a 768x768 resolution, offering more information to be shown in the generated images.\n",
    "* The model finetuned with [v-objective](https://arxiv.org/abs/2202.00512). The v-parameterization is particularly useful for numerical stability throughout the diffusion process to enable progressive distillation for models. For models that operate at higher resolution, it is also discovered that the v-parameterization avoids color shifting artifacts that are known to affect high resolution diffusion models, and in the video setting it avoids temporal color shifting that sometimes appears with epsilon-prediction used in Stable Diffusion v1. \n",
    "* The model also comes with a new diffusion model capable of running upscaling on the images generated. Upscaled images can be adjusted up to 4 times the original image. Provided as separated model, for more details please check [stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)\n",
    "* The model comes with a new refined depth architecture capable of preserving context from prior generation layers in an image-to-image setting. This structure preservation helps generate images that preserving forms and shadow of objects, but with different content.\n",
    "* The model comes with an updated inpainting module built upon the previous model. This text-guided inpainting makes switching out parts in the image easier than before.\n",
    "\n",
    "This notebook demonstrates how to download the model from the Hugging Face Hub and convert to OpenVINO IR format with the [Hugging Face Optimum Intel](https://huggingface.co/docs/optimum/intel/index) library. And how to use the model to generate sequence of images for infinite zoom video effect using [OpenVINO GenAI](https://github.com/openvinotoolkit/openvino.genai) that provides easy-to-use API.\n",
    "\n",
    "\n",
    "<img referrerpolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=5b5a4db0-7875-4bfb-bdbd-01698b5b1a77&file=notebooks/stable-diffusion-v2-infinite-zoom/stable-diffusion-v2-infinite-zoom.ipynb\" />\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "377238ed",
   "metadata": {},
   "source": [
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Stable Diffusion v2 Infinite Zoom Showcase](#Stable-Diffusion-v2-Infinite-Zoom-Showcase)\n",
    "    - [Stable Diffusion Text guided Inpainting](#Stable-Diffusion-Text-guided-Inpainting)\n",
    "- [Prerequisites](#Prerequisites)\n",
    "- [Load Stable Diffusion Inpaint pipeline using Optimum Intel](#Load-Stable-Diffusion-Inpaint-pipeline-using-Optimum-Intel)\n",
    "- [Zoom Video Generation](#Zoom-Video-Generation)\n",
    "- [Run Infinite Zoom video generation](#Run-Infinite-Zoom-video-generation)\n",
    "\n",
    "### Installation Instructions\n",
    "\n",
    "This is a self-contained example that relies solely on its own code.\n",
    "\n",
    "We recommend  running the notebook in a virtual environment. You only need a Jupyter server to start.\n",
    "For details, please refer to [Installation Guide](https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/README.md#-installation-guide)."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9ad7780c",
   "metadata": {},
   "source": [
    "## Stable Diffusion v2 Infinite Zoom Showcase\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "In this tutorial we consider how to use Stable Diffusion v2 model for generation sequence of images for infinite zoom video effect.\n",
    "To do this, we will need [`stabilityai/stable-diffusion-2-inpainting`](https://huggingface.co/stabilityai/stable-diffusion-2-inpainting) model.\n",
    "\n",
    "### Stable Diffusion Text guided Inpainting\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "In image editing, inpainting is a process of restoring missing parts of pictures. Most commonly applied to reconstructing old deteriorated images, removing cracks, scratches, dust spots, or red-eyes from photographs.\n",
    "\n",
    "But with the power of AI and the Stable Diffusion model, inpainting can be used to achieve more than that. For example, instead of just restoring missing parts of an image, it can be used to render something entirely new in any part of an existing picture. Only your imagination limits it.\n",
    "\n",
    "The workflow diagram explains how Stable Diffusion inpainting pipeline for inpainting works:\n",
    "\n",
    "![sd2-inpainting](https://github.com/openvinotoolkit/openvino_notebooks/assets/22090501/9ac6de45-186f-4a3c-aa20-825825a337eb)\n",
    "\n",
    "The pipeline has a lot of common with Text-to-Image generation pipeline discussed in previous section. Additionally to text prompt, pipeline accepts input source image and mask which provides an area of image which should be modified. Masked image encoded by VAE encoder into latent diffusion space and concatenated with randomly generated (on initial step only) or produced by U-Net latent generated image representation and used as input for next step denoising.\n",
    "\n",
    "Using this inpainting feature, decreasing image by certain margin and masking this border for every new frame we can create interesting Zoom Out video based on our prompt."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ee430286",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "install required packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ceaa943d",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip uninstall -q -y optimum optimum-intel optimum-onnx\n",
    "%pip install -q -U \"openvino>=2025.0\" \"openvino-genai>=2025.0\"\n",
    "%pip install -q \"diffusers>=0.14.0\" \"transformers==4.53.3\" \"gradio>=4.19\" \"torch==2.8\" \"torchvision==0.23.0\" Pillow opencv-python \"git+https://github.com/huggingface/optimum-intel.git\" --extra-index-url https://download.pytorch.org/whl/cpu"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "994be0f4",
   "metadata": {},
   "source": [
    "## Load Stable Diffusion Inpaint pipeline using Optimum Intel\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "[stable-diffusion-2-inpainting](https://huggingface.co/stabilityai/stable-diffusion-2-inpainting) is available for downloading via the [HuggingFace hub](https://huggingface.co/models). We will use optimum-cli interface for exporting it into OpenVINO Intermediate Representation (IR) format.\n",
    "\n",
    " Optimum CLI interface for converting models supports export to OpenVINO (supported starting optimum-intel 1.12 version).\n",
    "General command format:\n",
    "\n",
    "```bash\n",
    "optimum-cli export openvino --model <model_id_or_path> --task <task> <output_dir>\n",
    "```\n",
    "\n",
    "where `task` is the task to export the model for, if not specified, the task will be auto-inferred based on the model.\n",
    "\n",
    "You can find a mapping between tasks and model classes in Optimum TaskManager [documentation](https://huggingface.co/docs/optimum/exporters/task_manager).\n",
    "\n",
    "Additionally, you can specify weights compression `--weight-format` for the model compression. Please note, that for INT8/INT4, it is necessary to install nncf.\n",
    "\n",
    "Full list of supported arguments available via `--help`\n",
    "For more details and examples of usage, please check [optimum documentation](https://huggingface.co/docs/optimum/intel/inference#export).\n",
    "\n",
    "\n",
    "For running the Stable Diffusion model, we will use [OpenVINO GenAI](https://github.com/openvinotoolkit/openvino.genai) that provides easy-to-use API for running text generation. Firstly we will create pipeline with `InpaintingPipeline`. You can see more details in [Image Python Generation Pipeline Example](https://github.com/openvinotoolkit/openvino.genai/tree/releases/2025/0/samples/python/image_generation#run-inpainting-pipeline).\n",
    "Then we run the `generate` method and get the image tokens and then convert them into the image using `Image.fromarray` from PIL. Also we convert the input images to `ov.Tensor` using `image_to_tensor` function. \n",
    "\n",
    "Select device from dropdown list for running inference using OpenVINO."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "461813a8-a2a6-4170-b6f2-9efb92b1b668",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "from pathlib import Path\n",
    "\n",
    "if not Path(\"notebook_utils.py\").exists():\n",
    "    r = requests.get(\n",
    "        url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
    "    )\n",
    "    open(\"notebook_utils.py\", \"w\").write(r.text)\n",
    "\n",
    "if not Path(\"cmd_helper.py\").exists():\n",
    "    r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/cmd_helper.py\")\n",
    "    open(\"cmd_helper.py\", \"w\").write(r.text)\n",
    "\n",
    "# Read more about telemetry collection at https://github.com/openvinotoolkit/openvino_notebooks?tab=readme-ov-file#-telemetry\n",
    "from notebook_utils import collect_telemetry\n",
    "\n",
    "collect_telemetry(\"stable-diffusion-v2-infinite-zoom.ipynb\")\n",
    "\n",
    "from notebook_utils import device_widget\n",
    "\n",
    "device = device_widget()\n",
    "\n",
    "device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7333f043-20b4-4125-ba1c-506d7a72e8a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openvino as ov\n",
    "\n",
    "from cmd_helper import optimum_cli\n",
    "\n",
    "\n",
    "MODEL_ID = \"stabilityai/stable-diffusion-2-inpainting\"\n",
    "MODEL_DIR = Path(\"sd2_inpainting\")\n",
    "\n",
    "optimum_cli(MODEL_ID, MODEL_DIR, additional_args={\"weight-format\": \"fp16\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a424af25",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openvino_genai as ov_genai\n",
    "\n",
    "\n",
    "pipe = ov_genai.InpaintingPipeline(MODEL_DIR, device.value)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "a0a54ba0",
   "metadata": {},
   "source": [
    "## Zoom Video Generation\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "For achieving zoom effect, we will use inpainting to expand images beyond their original borders.\n",
    "We run our `InpaintingPipeline` in the loop, where each next frame will add edges to previous. The frame generation process illustrated on diagram below:\n",
    "\n",
    "![frame generation)](https://user-images.githubusercontent.com/29454499/228739686-436f2759-4c79-42a2-a70f-959fb226834c.png)\n",
    "\n",
    "After processing current frame, we decrease size of current image by mask size pixels from each side and use it as input for next step. Changing size of mask we can influence the size of painting area and image scaling.\n",
    "\n",
    "There are 2 zooming directions:\n",
    "\n",
    "* Zoom Out - move away from object\n",
    "* Zoom In - move closer to object\n",
    "\n",
    "Zoom In will be processed in the same way as Zoom Out, but after generation is finished, we record frames in reversed order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "051acf7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Union\n",
    "\n",
    "import PIL\n",
    "from PIL import Image\n",
    "import cv2\n",
    "from tqdm import trange\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "def image_to_tensor(image: Image) -> ov.Tensor:\n",
    "    pic = image.convert(\"RGB\")\n",
    "    image_data = np.array(pic.getdata()).reshape(1, pic.size[1], pic.size[0], 3).astype(np.uint8)\n",
    "    return ov.Tensor(image_data)\n",
    "\n",
    "\n",
    "def generate_video(\n",
    "    pipe,\n",
    "    prompt: Union[str, list[str]],\n",
    "    negative_prompt: Union[str, list[str]],\n",
    "    guidance_scale: float = 7.5,\n",
    "    num_inference_steps: int = 20,\n",
    "    num_frames: int = 20,\n",
    "    mask_width: int = 128,\n",
    "    seed: int = 9999,\n",
    "    zoom_in: bool = False,\n",
    "):\n",
    "    \"\"\"\n",
    "    Zoom video generation function\n",
    "\n",
    "    Parameters:\n",
    "      pipe (OVStableDiffusionInpaintingPipeline): inpainting pipeline.\n",
    "      prompt (str or List[str]): The prompt or prompts to guide the image generation.\n",
    "      negative_prompt (str or List[str]): The negative prompt or prompts to guide the image generation.\n",
    "      guidance_scale (float, *optional*, defaults to 7.5):\n",
    "                Guidance scale as defined in Classifier-Free Diffusion Guidance(https://arxiv.org/abs/2207.12598).\n",
    "                guidance_scale is defined as `w` of equation 2.\n",
    "                Higher guidance scale encourages to generate images that are closely linked to the text prompt,\n",
    "                usually at the expense of lower image quality.\n",
    "      num_inference_steps (int, *optional*, defaults to 50): The number of denoising steps for each frame. More denoising steps usually lead to a higher quality image at the expense of slower inference.\n",
    "      num_frames (int, *optional*, 20): number frames for video.\n",
    "      mask_width (int, *optional*, 128): size of border mask for inpainting on each step.\n",
    "      zoom_in (bool, *optional*, False): zoom mode Zoom In or Zoom Out.\n",
    "    Returns:\n",
    "      output_path (str): Path where generated video loacated.\n",
    "    \"\"\"\n",
    "\n",
    "    height = 512\n",
    "    width = height\n",
    "\n",
    "    current_image = PIL.Image.new(mode=\"RGBA\", size=(height, width))\n",
    "    mask_image = np.array(current_image)[:, :, 3]\n",
    "    mask_image = PIL.Image.fromarray(255 - mask_image).convert(\"RGB\")\n",
    "    current_image = current_image.convert(\"RGB\")\n",
    "    current_image = image_to_tensor(current_image)\n",
    "    mask_image = image_to_tensor(mask_image)\n",
    "    image_tensors = pipe.generate(\n",
    "        prompt=prompt,\n",
    "        negative_prompt=negative_prompt,\n",
    "        image=current_image,\n",
    "        guidance_scale=guidance_scale,\n",
    "        mask_image=mask_image,\n",
    "        num_inference_steps=num_inference_steps,\n",
    "    )\n",
    "    init_images = []\n",
    "    for image_tensor in image_tensors.data:\n",
    "        init_images.append(PIL.Image.fromarray(image_tensor))\n",
    "\n",
    "    image_grid(init_images, rows=1, cols=1)\n",
    "\n",
    "    num_outpainting_steps = num_frames\n",
    "    num_interpol_frames = 30\n",
    "\n",
    "    current_image = init_images[0]\n",
    "    all_frames = []\n",
    "    all_frames.append(current_image)\n",
    "    for i in trange(\n",
    "        num_outpainting_steps,\n",
    "        desc=f\"Generating {num_outpainting_steps} additional images...\",\n",
    "    ):\n",
    "        prev_image_fix = current_image\n",
    "\n",
    "        prev_image = shrink_and_paste_on_blank(current_image, mask_width)\n",
    "\n",
    "        current_image = prev_image\n",
    "\n",
    "        # create mask (black image with white mask_width width edges)\n",
    "        mask_image = np.array(current_image)[:, :, 3]\n",
    "        mask_image = PIL.Image.fromarray(255 - mask_image).convert(\"RGB\")\n",
    "\n",
    "        # inpainting step\n",
    "        current_image = current_image.convert(\"RGB\")\n",
    "        current_image = image_to_tensor(current_image)\n",
    "        mask_image = image_to_tensor(mask_image)\n",
    "        image_tensor = pipe.generate(\n",
    "            prompt=prompt,\n",
    "            negative_prompt=negative_prompt,\n",
    "            image=current_image,\n",
    "            guidance_scale=guidance_scale,\n",
    "            mask_image=mask_image,\n",
    "            num_inference_steps=num_inference_steps,\n",
    "        )\n",
    "        current_image = PIL.Image.fromarray(image_tensor.data[0])\n",
    "        current_image.paste(prev_image, mask=prev_image)\n",
    "\n",
    "        # interpolation steps bewteen 2 inpainted images (=sequential zoom and crop)\n",
    "        for j in range(num_interpol_frames - 1):\n",
    "            interpol_image = current_image\n",
    "            interpol_width = round((1 - (1 - 2 * mask_width / height) ** (1 - (j + 1) / num_interpol_frames)) * height / 2)\n",
    "            interpol_image = interpol_image.crop(\n",
    "                (\n",
    "                    interpol_width,\n",
    "                    interpol_width,\n",
    "                    width - interpol_width,\n",
    "                    height - interpol_width,\n",
    "                )\n",
    "            )\n",
    "\n",
    "            interpol_image = interpol_image.resize((height, width))\n",
    "\n",
    "            # paste the higher resolution previous image in the middle to avoid drop in quality caused by zooming\n",
    "            interpol_width2 = round((1 - (height - 2 * mask_width) / (height - 2 * interpol_width)) / 2 * height)\n",
    "            prev_image_fix_crop = shrink_and_paste_on_blank(prev_image_fix, interpol_width2)\n",
    "            interpol_image.paste(prev_image_fix_crop, mask=prev_image_fix_crop)\n",
    "            all_frames.append(interpol_image)\n",
    "        all_frames.append(current_image)\n",
    "\n",
    "    video_file_name = f\"infinite_zoom_{'in' if zoom_in else 'out'}\"\n",
    "    fps = 30\n",
    "    save_path = video_file_name + \".mp4\"\n",
    "    write_video(save_path, all_frames, fps, reversed_order=zoom_in)\n",
    "\n",
    "    return save_path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9666757",
   "metadata": {},
   "outputs": [],
   "source": [
    "def shrink_and_paste_on_blank(current_image: PIL.Image.Image, mask_width: int):\n",
    "    \"\"\"\n",
    "    Decreases size of current_image by mask_width pixels from each side,\n",
    "    then adds a mask_width width transparent frame,\n",
    "    so that the image the function returns is the same size as the input.\n",
    "\n",
    "    Parameters:\n",
    "        current_image (PIL.Image): input image to transform\n",
    "        mask_width (int): width in pixels to shrink from each side\n",
    "    Returns:\n",
    "       prev_image (PIL.Image): resized image with extended borders\n",
    "    \"\"\"\n",
    "\n",
    "    height = current_image.height\n",
    "    width = current_image.width\n",
    "\n",
    "    # shrink down by mask_width\n",
    "    prev_image = current_image.resize((height - 2 * mask_width, width - 2 * mask_width))\n",
    "    prev_image = prev_image.convert(\"RGBA\")\n",
    "    prev_image = np.array(prev_image)\n",
    "\n",
    "    # create blank non-transparent image\n",
    "    blank_image = np.array(current_image.convert(\"RGBA\")) * 0\n",
    "    blank_image[:, :, 3] = 1\n",
    "\n",
    "    # paste shrinked onto blank\n",
    "    blank_image[mask_width : height - mask_width, mask_width : width - mask_width, :] = prev_image\n",
    "    prev_image = PIL.Image.fromarray(blank_image)\n",
    "\n",
    "    return prev_image\n",
    "\n",
    "\n",
    "def image_grid(imgs: list[PIL.Image.Image], rows: int, cols: int):\n",
    "    \"\"\"\n",
    "    Insert images to grid\n",
    "\n",
    "    Parameters:\n",
    "        imgs (List[PIL.Image.Image]): list of images for making grid\n",
    "        rows (int): number of rows in grid\n",
    "        cols (int): number of columns in grid\n",
    "    Returns:\n",
    "        grid (PIL.Image): image with input images collage\n",
    "    \"\"\"\n",
    "    assert len(imgs) == rows * cols\n",
    "\n",
    "    w, h = imgs[0].size\n",
    "    grid = PIL.Image.new(\"RGB\", size=(cols * w, rows * h))\n",
    "\n",
    "    for i, img in enumerate(imgs):\n",
    "        grid.paste(img, box=(i % cols * w, i // cols * h))\n",
    "    return grid\n",
    "\n",
    "\n",
    "def write_video(\n",
    "    file_path: str,\n",
    "    frames: list[PIL.Image.Image],\n",
    "    fps: float,\n",
    "    reversed_order: bool = True,\n",
    "    gif: bool = True,\n",
    "):\n",
    "    \"\"\"\n",
    "    Writes frames to an mp4 video file and optionaly to gif\n",
    "\n",
    "    Parameters:\n",
    "        file_path (str): Path to output video, must end with .mp4\n",
    "        frames (List of PIL.Image): list of frames\n",
    "        fps (float): Desired frame rate\n",
    "        reversed_order (bool): if order of images to be reversed (default = True)\n",
    "        gif (bool): save frames to gif format (default = True)\n",
    "    Returns:\n",
    "        None\n",
    "    \"\"\"\n",
    "    if reversed_order:\n",
    "        frames.reverse()\n",
    "\n",
    "    w, h = frames[0].size\n",
    "    fourcc = cv2.VideoWriter_fourcc(\"m\", \"p\", \"4\", \"v\")\n",
    "    writer = cv2.VideoWriter(file_path, fourcc, fps, (w, h))\n",
    "\n",
    "    for frame in frames:\n",
    "        np_frame = np.array(frame.convert(\"RGB\"))\n",
    "        cv_frame = cv2.cvtColor(np_frame, cv2.COLOR_RGB2BGR)\n",
    "        writer.write(cv_frame)\n",
    "\n",
    "    writer.release()\n",
    "    if gif:\n",
    "        frames[0].save(\n",
    "            file_path.replace(\".mp4\", \".gif\"),\n",
    "            save_all=True,\n",
    "            append_images=frames[1:],\n",
    "            duratiobn=len(frames) / fps,\n",
    "            loop=0,\n",
    "        )"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "66fd066a",
   "metadata": {},
   "source": [
    "## Run Infinite Zoom video generation\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eeb67824-7d1c-4680-8f3c-e55edc5b36eb",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "\n",
    "if not Path(\"gradio_helper.py\").exists():\n",
    "    r = requests.get(\n",
    "        url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/stable-diffusion-v2-infinite-zoom/gradio_helper.py\"\n",
    "    )\n",
    "    open(\"gradio_helper.py\", \"w\").write(r.text)\n",
    "\n",
    "from gradio_helper import make_demo_zoom_video\n",
    "\n",
    "demo = make_demo_zoom_video(pipe, generate_video)\n",
    "\n",
    "try:\n",
    "    demo.queue().launch()\n",
    "except Exception:\n",
    "    demo.queue().launch(share=True)\n",
    "# if you are launching remotely, specify server_name and server_port\n",
    "# demo.launch(server_name='your server name', server_port='server port in int')\n",
    "# Read more in the docs: https://gradio.app/docs/"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  },
  "openvino_notebooks": {
   "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/notebooks/stable-diffusion-v2/stable-diffusion-v2-infinite-zoom.gif?raw=true",
   "tags": {
    "categories": [
     "Model Demos",
     "AI Trends"
    ],
    "libraries": [],
    "other": [
     "Stable Diffusion"
    ],
    "tasks": [
     "Text-to-Image",
     "Image Inpainting",
     "Text-to-Video"
    ]
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
